<template>
    <div class="carousel-container">
        <!-- 左侧轮播图 -->
        <el-carousel class="carousel-box" height="436px" indicator-position="none" arrow="never" :interval="6000"
            :autoplay="false" ref="carouselRef" @change="handleChange" v-if="games.length > 0">
            <el-carousel-item v-for="(game, index) in games" :key="index">
                <div class="carousel-item" v-if="game.redirectType == 'app'"
                    @click="navigateToGameDetail(game.gameId || game.id)">
                    <img :src="game.imageUrl" alt="失控进化" class="carousel-img">
                    <div class="carousel-content">
                        <h2 class="game-title">{{ game.gameName || game.title }}</h2>
                        <p class="game-subtitle">{{ game.gameSlogan || '' }}</p>
                        <el-button type="primary" class="play-btn"
                            @click.stop="gameDetailHandlePlayGame(game.gameId || game.id)">
                            <el-icon>
                                <img src="@/assets/svgs/thunder_1.svg" alt="秒玩图标" />
                            </el-icon>
                            秒玩
                        </el-button>
                    </div>
                </div>
                <div class="carousel-item" v-if="game.redirectType == 'h5'" @click="openExternalBrowser(game)">
                    <img :src="game.imageUrl" alt="失控进化" class="carousel-img">
                    <div class="carousel-content">
                        <h2 class="game-title">{{ game.title }}</h2>
                        <!-- <p class="game-subtitle">{{ game.title }}</p> -->
                    </div>
                </div>
            </el-carousel-item>
        </el-carousel>

    <!-- 右侧游戏列表 -->
    <div class="games-list">
      <div v-for="(game, index) in games" :key="index" class="game-item" :class="{ active: index === selectedIndex }"
        @click="selectGame(index)">
        <div class="game-icon">
          <img :src="game.thumbnail" :alt="game.title">
        </div>
        <div class="game-name ellipsis2">
          {{ game.title }}
          <!-- <span v-if="game.subtitle" class="game-subtitle">({{ game.subtitle }})</span> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getBanner, getHomeLayout, getGameNew, getWeekHot, getFreeAccount } from '@/api';
import { useLoginCheck, handlePlayGame } from "@/utils/auth.js";
import { domesticUserCenter } from 'ld-web-sdk';
// 路由实例
const route = useRoute()
const router = useRouter()

// 秒玩游戏状态
const isPlaying = ref(false);
// 游戏ID
const gameId = ref('');



// 游戏列表数据
const games = ref([])
const carouselRef = ref(null)

// 选中的游戏索引
const selectedIndex = ref(0)

// 轮播定时器
let carouselTimer = null

// 轮播间隔（毫秒）
const carouselInterval = 6000



onMounted(() => {
    let params = {
        location: 'home'
    }
    getBanner(params).then(res => {
        var banners = res.banners
        games.value = banners;
        
        // 数据加载完成后开始自定义轮播
        startCustomCarousel()
    })
    
    // 组件卸载时清理定时器
    onBeforeUnmount(() => {
        if (carouselTimer) {
            clearInterval(carouselTimer)
            carouselTimer = null
        }
    })
})

// 开始自定义轮播
const startCustomCarousel = () => {
    // 清除已存在的定时器
    if (carouselTimer) {
        clearInterval(carouselTimer)
        carouselTimer = null
    }
    
    // 设置新的轮播定时器
    carouselTimer = setInterval(() => {
        if (games.value.length > 0 && carouselRef.value) {
            // 计算下一个要显示的索引
            const nextIndex = (selectedIndex.value + 1) % games.value.length
            // 切换轮播图
            carouselRef.value.setActiveItem(nextIndex)
            selectedIndex.value = nextIndex
        }
    }, carouselInterval)
}

// 选择游戏
const selectGame = (index) => {
    selectedIndex.value = index
    // 直接切换轮播图
    carouselRef.value.setActiveItem(index)
    
    // 重置轮播定时器，确保从当前项开始计算间隔
    startCustomCarousel()
}

// 引入登录检查模块
const { checkAndPerform } = useLoginCheck()
// 登录
const login = () => {
  // 检查登录并执行操作
  checkAndPerform(() => {
    // 登录成功后执行的操作
    console.log("登录成功后执行的操作", domesticUserCenter);
  })
}
// 导航到游戏详情页面
const navigateToGameDetail = (id) => {
  // 执行路由跳转
  router.push({
    path: `/cloudGaming/detail/${id}`,
  })
}
// 秒玩游戏处理函数
const gameDetailHandlePlayGame = (id) => {
  gameId.value = id;
  isPlaying.value = true;
  // 传入目标类型:1=云游戏;2=云电脑
  handlePlayGame(id, "1", handlePlayGameCallback, 1);
}
// 使用全局handlePlayGame方法
const handlePlayGameCallback = (status, data) => {
  switch (status) {
    case "cancel": //取消
      isPlaying.value = false;
      break;
    case "confirm": //确认
      isPlaying.value = false;
      // 传入目标类型:1=云游戏;2=云电脑
      handlePlayGame(gameId.value, "1", handlePlayGameCallback, 0);
      break;
  }
};

// 打开外部浏览器
const openExternalBrowser = (game) => {
  if (game.redirectType === 'h5' && game.redirectUrl) {
    // 使用浏览器打开游戏链接
    window.chrome.webview.postMessage({ action: 'openExternalBrowser', url: game.redirectUrl });
  }
}

// 轮播图切换
const handleChange = (index) => {
  selectedIndex.value = index
}
</script>

<style lang="scss" scoped>
.carousel-container {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  height: 440px;

  /* 轮播图样式 */
  .carousel-box {
    width: 775px;
    height: 440px;
    overflow: hidden;
    border-radius: 4px;
  }

  .carousel-item {
    position: relative;
    width: 100%;
    height: 100%;
    cursor: pointer;
  }

  .carousel-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .carousel-content {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    padding: 40px;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    color: white;
    background: linear-gradient(to bottom, transparent 0%, rgba(0, 0, 0, 0.8) 100%);
  }

  .game-title {
    color: #fff;
    font-size: 24px;
    font-weight: bold;
    margin: 0 0 8px 0;
    text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
  }

  .game-subtitle {
    font-size: 20px;
    margin: 0 0 16px 0;
    opacity: 0.8;
  }

  .play-btn {
    width: 70px;
    height: 32px;
    font-size: 14px;
    font-weight: bold;
    background-color: #fff;
    border-color: #fff;
    color: #333;
  }

  .play-btn:hover {
    opacity: 0.85;
  }

  /* 游戏列表样式 */
  .games-list {
    width: 208px;
    height: 436px;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .game-item {
    height: 56px;
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px;
    border-radius: 4px;
    cursor: pointer;
    // transition: all 0.3s ease;
    box-sizing: border-box;
    position: relative;
  }

  .game-item:hover {
    background-color: rgba(255, 255, 255, 0.1);
    transition: background-color 0.2s ease;
  }

  .game-item.active {
    &::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      border-radius: 4px;
      background-color: rgba(255, 255, 255, 0.1);
      transform-origin: left;
      transform: scaleX(0);
      animation: load 6s linear forwards;
    }
  }

  .game-item.active {
    background-color: #1c1f22;
  }

  @keyframes load {
    to {
      transform: scaleX(1);
    }
  }

  .game-icon {
    width: 40px;
    height: 40px;
    border-radius: 4px;
    overflow: hidden;
  }

  .game-icon img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .game-name {
    flex: 1;
    color: #fff;
    font-size: 14px;
    font-weight: 500;
  }

  .game-subtitle {
    font-size: 12px;
    opacity: 0.7;
  }
}
</style>
